from rest_framework import serializers

from sqtp.models import Project, Environment, User
from sqtp.serializers import UserSerializer


class ProjectSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    admin_id = serializers.IntegerField(write_only=True)
    admin = UserSerializer(read_only=True)

    class Meta:
        model = Project
        fields = ['id', 'admin', 'admin_id', 'desc', 'name', 'status', 'version', 'create_time', 'update_time',
                  'status']


class EnvironmentSerializer(serializers.ModelSerializer):
    project = ProjectSerializer(read_only=True)
    project_id = serializers.IntegerField(write_only=True)
    category = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()
    os = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H', read_only=True)

    def get_category(self, obj):
        return obj.get_category_display()

    def get_status(self, obj):
        return obj.get_status_display()

    def get_os(self, obj):
        return obj.get_os_display()

    '''
    综合型
    '''
    def validate(self, attrs):
        return attrs

    '''
    单个字段
    '''
    def validate_project_id(self, project_id):
        if Project.objects.filter(pk=project_id).count() == 0:
            return serializers.ValidationError("请传递正确的project_id")
        return project_id
    class Meta:
        model = Environment
        fields = ['category', 'desc', 'ip', 'os', 'port', 'project_id', 'status','create_time','update_time','project','id']
